import os
import django
import sys

pro_dir = os.getcwd()
sys.path.append(pro_dir)
sys.path.append(pro_dir+'/utils/code')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mitagger.settings")

from home.models import Image, Tag, Ontology
import excute
import csv
from xml.dom import minidom



def getRecommendResultList(recommend_result, image_filename):
    result = list()
    for annotate in recommend_result:
        for tag_info in annotate['annotatedClasses']:
            tag_id = tag_info['@id']
            tag_obj = Tag.objects.get(id=tag_id)
            tag_result = {
                'imageFileName': image_filename,
                'tagID': tag_obj.id,
                'tagName': tag_obj.name,
                'tag_fullID': tag_obj.fullId,
                'ontologyName':tag_obj.ontology.name,
                'ontologyVirtualId': tag_obj.ontology.virtual_id,
                'tagTypeName': 'recommend',
            }
            result.append(tag_result)
    return result

def writeResultToCSV(file_obj, results):
    row_list = list()
    for tag_infos in results:
        row = list()
        for key in tag_infos:
            row.append(tag_infos[key])
        row_list.append(row)
    file_obj.writerows(row_list)

def writeResultToDoc(xml_root, xml_doc, results):
    for tag_infos in results:
        tag_node = xml_doc.createElement("Tag")
        for node_name in tag_infos:
            info_node = xml_doc.createElement("%s" % node_name)
            data = xml_doc.createTextNode("%s" % tag_infos[node_name])
            info_node.appendChild(data)
            tag_node.appendChild(info_node)
        xml_root.appendChild(tag_node)


def getRecommendsForImages(image_list, csv_file_obj, xml_root, xml_doc):
    for image_obj in image_list:
        image_filename = image_obj.file_name
        print 'getting data for image: '+ image_filename
        image_legend = image_obj.legend + ' ' + image_obj.title
        result = excute.mainMethod(image_legend, 'all')
        results_list = getRecommendResultList(result, image_filename)
        print 'writing result to csv & xml file'
        writeResultToCSV(csv_file_obj, results_list)
        writeResultToDoc(xml_root, xml_doc, results_list)

def getAllImageTags():
    image_count = Image.objects.count()
    excute.importData()
    csv_filename = 'allTags.csv'
    csv_writer = csv.writer(open(csv_filename, 'wb'), delimiter=',')
    header = {
        'imageFileName': '',
        'tagID': '',
        'tagName': '',
        'tag_fullID': '',
        'ontologyName': '',
        'ontologyVirtualId': '',
        'tagTypeName': ''
    }
    csv_writer.writerow([i for i in header])
    doc  = minidom.Document()
    root = doc.createElement("Data")
    doc.appendChild(root)
    print 'start process'
    offset = 0
    count = 50
    while image_count > 0:
        image_list = Image.objects.all()[offset:count]
        offset += count
        image_count -= count
        getRecommendsForImages(image_list, csv_writer, root, doc)
    print 'write xml dom to xml file'
    xml_file = open('allTags.xml', 'w')
    xml_file.write(doc.toxml("utf-8"))
    xml_file.close()
    del csv_writer
    print 'process ended'


if __name__ == '__main__':
    django.setup()
    getAllImageTags()
